<template>
  <div class="api-manage-container">
    <div class="toolbar">
      <el-button type="primary" @click="handleCreateApi">
        <el-icon><Plus /></el-icon>新建接口
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索接口名称"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="apiList" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="接口名称" />
      <el-table-column prop="path" label="接口路径" />
      <el-table-column prop="method" label="请求方法">
        <template #default="{ row }">
          <el-tag :type="getMethodTagType(row.method)">{{ row.method }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="ApiStatus.Enabled"
            :inactive-value="ApiStatus.Disabled"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="primary" link @click="handleTest(row)">
              测试
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <ApiForm
      v-model:visible="formVisible"
      :edit-data="editingData"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { Plus, Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ApiForm from "./components/ApiForm.vue";
import {
  getApiList,
  createApi,
  updateApi,
  deleteApi,
  testApi,
} from "@/api/apiManage";
import type { ApiConfig } from "@/types/api";
import { ApiMethod, ApiStatus } from "@/types/api";

const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const formVisible = ref(false);
const editingData = ref<ApiConfig | null>(null);
const apiList = ref<ApiConfig[]>([]);

const getMethodTagType = (method: ApiMethod) => {
  const types: Record<string, string> = {
    [ApiMethod.GET]: "success",
    [ApiMethod.POST]: "primary",
    [ApiMethod.PUT]: "warning",
    [ApiMethod.DELETE]: "danger",
  };
  return types[method] || "info";
};

const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      keyword: searchQuery.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    };
    const { list, total: totalCount } = await getApiList(params);
    apiList.value = list;
    total.value = totalCount;
  } catch (error) {
    console.error("加载API列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleCreateApi = () => {
  editingData.value = null;
  formVisible.value = true;
};

const handleEdit = (row: ApiConfig) => {
  editingData.value = row;
  formVisible.value = true;
};

const handleTest = async (row: ApiConfig) => {
  if (!row.id) return;

  try {
    const { success, message, data } = await testApi(row.id);
    if (success) {
      ElMessage.success("接口测试成功");
      console.log("测试结果:", data);
    } else {
      ElMessage.error(message || "接口测试失败");
    }
  } catch (error) {
    console.error("测试接口失败:", error);
  }
};

const handleDelete = (row: ApiConfig) => {
  if (!row.id) return;

  ElMessageBox.confirm("确定要删除该接口吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    try {
      await deleteApi(row.id);
      ElMessage.success("删除成功");
      loadData();
    } finally {
      loading.value = false;
    }
  });
};

const handleStatusChange = async (row: ApiConfig) => {
  if (!row.id) return;

  try {
    await updateApi(row.id, { status: row.status });
    ElMessage.success("状态更新成功");
  } catch (error) {
    console.error("更新状态失败:", error);
    // 回滚状态
    row.status =
      row.status === ApiStatus.Enabled ? ApiStatus.Disabled : ApiStatus.Enabled;
  }
};

const handleFormSubmit = async (data: ApiConfig) => {
  loading.value = true;
  try {
    if (data.id) {
      await updateApi(data.id, data);
      ElMessage.success("更新成功");
    } else {
      await createApi(data);
      ElMessage.success("创建成功");
    }
    loadData();
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadData();
};

watch([searchQuery], () => {
  currentPage.value = 1;
  loadData();
});

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.api-manage-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 